package com.lz.yz.outing.controller;


import com.lz.yz.base.entity.ReturnValue;
import com.lz.yz.base.util.HttpClientUtils;
import com.lz.yz.order.entity.Orders;
import com.lz.yz.order.enumeration.PayTypeStatus;
import com.lz.yz.order.service.OrdersService;
import com.lz.yz.outing.config.InitConfig;
import com.lz.yz.outing.config.WechatConfig;
import com.lz.yz.outing.entity.MessageFrom;
import com.lz.yz.outing.entity.WechatPostData;
import com.lz.yz.outing.service.WechatPushService;
import com.lz.yz.outing.service.WechatService;
import com.lz.yz.outing.util.ToolUtil;
import com.lz.yz.outing.util.Util;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping(value = "/wechat")
public class WechatController {
    private static final Logger logger = LoggerFactory.getLogger(WechatController.class);

    @Autowired
    WechatService wechatService;

    @Autowired
    OrdersService ordersService;

    @Autowired
    InitConfig initConfig;

    @Autowired
    WechatPushService wechatPushService;

    @ApiOperation(value="微信支付统一下单接口")
    @RequestMapping(value = "/makeWechatOrder", method = RequestMethod.POST)
    public ReturnValue makeWechatOrder(@RequestBody Map<String, Object> map, HttpServletRequest request)throws Exception{
        return this.wechatService.makeWechatOrder(map, request);
    }


    @ApiOperation(value="微信支付回调接口")
    @RequestMapping(value = "/wechat_notify", method = RequestMethod.POST)
    public void wechatNotifyUrl(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        final String resultOK = "<xml>"
                + "<return_code>SUCCESS</return_code>"
                + "<return_msg>OK</return_msg>"
                + "</xml>";
        String resultFail = "<xml>"
                + "<return_code>FAIL</return_code>"
                + "</xml>";
        // post 过来的xml
        WechatPostData postData;
        try {
            ServletInputStream in = request.getInputStream();
            String xmlMsg = ToolUtil.inputStream2String(in);
            postData = (WechatPostData) Util.getObjectFromXML(xmlMsg, WechatPostData.class);
            if (postData.getReturn_code().equalsIgnoreCase("success") && postData.getResult_code().equalsIgnoreCase("success")){

                Orders orderBean = ordersService.findBy("orderNo",postData.getOut_trade_no());

                if (orderBean == null){
                    response.getWriter().write(resultFail);
                    return;
                }
                Orders order = new Orders();
                BeanUtils.copyProperties(orderBean,order);
                //修改订单支付状态
                order.setPayType(PayTypeStatus.WECHAT.getStatusValue());

                if(!ordersService.orderNotify(order,postData.getAttach())){
                    response.getWriter().write(resultFail);
                    return;
                }
                response.getWriter().write(resultOK);
            } else {
                logger.error("支付回调失败:"
                        + postData.getReturn_msg()
                        + ",错误码："
                        + postData.getErr_code()
                        + "，错误描述:"
                        + postData.getErr_code_des());
                response.getWriter().write(resultFail);
            }

        } catch (IOException e) {
            logger.error("微信支付回调失败", e);
        }
    }


    @ApiOperation(value="微信公众号登录授权获取access_token")
    @RequestMapping(value = "/accessToken", method = RequestMethod.POST)
    public ReturnValue accessToken(@RequestBody Map<String, Object> map){
        String code = (String) map.get("code");
        String url = WechatConfig.ACCESS_TOKEN_URL + "?appid="+initConfig.getWechatAppid()+"&secret="+initConfig.getWechatSecret()+"&code="+code+"&grant_type=authorization_code";
        JSONObject result = HttpClientUtils.httpGet(url);
        String openid = (String) result.get("openid");
        if(openid==null)
            return ReturnValue.generateFalseReturnValue("code无效");
        return ReturnValue.generateTrueReturnValue(openid);
    }

    @ApiOperation(value="获取jsapi accessToken")
    @RequestMapping(value = "/jsapiAccessToken", method = RequestMethod.GET)
    public ReturnValue jsApiAccessToken(){
        String accessToken = wechatService.getAccessToken();
        return ReturnValue.generateTrueReturnValue(accessToken);
    }

    @ApiOperation(value="获得JS-SDK权限验证的签名")
    @RequestMapping(value = "/getSign", method = RequestMethod.GET)
    public ReturnValue getSign(String url){
        return wechatService.getSign(url);
    }


    @ApiOperation(value="企业付款")
    @RequestMapping(value = "/wechatTransfers", method = RequestMethod.POST)
    public ReturnValue wechatPayRefund(@RequestBody Map<String, Object> map,HttpServletRequest request)throws Exception{
        return this.wechatService.wechatTransfers(map,request);
    }

    @ApiOperation(value="推送")
    @RequestMapping(value = "/push", method = RequestMethod.GET)
    public ReturnValue push(String openId) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            MessageFrom messageFrom=new MessageFrom("你有freestyle吗？"+i,"你的良心不会痛吗？","扎心了，老铁","还有这种操作？","油腻");
            wechatPushService.reviewUser(messageFrom,openId,WechatConfig.WECHAT_PUSH_URL+wechatService.getAccessToken());
            Thread.sleep(500);
        }
        return ReturnValue.generateTrueReturnValue(200);
    }
}
